<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/27 0027
 * Time: 上午 9:54
 */

namespace Api\Controller;

use Think\Controller;

class GoodsController extends Controller
{
    /**
     * 获取菜品的分类
     */
    public function getCategory()
    {
        $store_id = I('post.store_id');
        if ($store_id) {
            $where = "store_id='$store_id'";
        } else {
            $where = "1=1";
        }
        $result = M("dishes_category")->where($where)->select();

        if ($result) {
            $this->ajaxReturn(array('state' => 1, 'data' => $result), 'json');
        } else {
            //没查到东西
            $this->ajaxReturn(array('state' => -1, 'data' => $result), 'json');
        }
    }

    /**
     * 获取菜品
     */
    public function getGoods()
    {
        $map['num'] = array('gt', 1);
        $map['is_up'] = 1;

        //根据分类查出分类下所有商品
        $result = M('dishes_category')->field(array('id as category_id','name as category_name'))->select();
        foreach ($result as $k=>$v){
            $map['category_id'] = $v['category_id'];
            $result[$k]['goods'] = M('dishes')->where($map)->select();
        }

         if ($result) {
            $this->ajaxReturn(array("state" => 1, 'data' => $result), 'json');
        } else {
            $this->ajaxReturn(array("state" => -1), 'json');
        }
    }

    /**
     * 获取菜品的属性
     */
    public function getAttributes()
    {
        $dishId = I('request.dishId');

        if (empty($dishId)) {
            $this->ajaxReturn(array('state' => 2, 'message' => '菜品id不能为空'), 'json');
        } else {
            $result = M('dish_attributes')->alias("d")->join("join meal_dishes as v on d.dish_id=v.id")
                ->join('meal_attributes c ON c.id = d.attribute_id')
                ->field('d.id,d.id as id,d.dish_id as dish_id,v.name as name,d.attribute_value_name as attribute_value_name,d.attribute_value as attribute_value,
                d.is_need as is_need,c.name_attribute as attribute_name,d.attribute_value_price as attribute_value_price')->
                where("d.dish_id='$dishId' and v.is_up = '1'")
                ->select();


            foreach ($result as &$v) {
                $v['attribute_value_name'] = implode(",", array_filter(explode(",", $v['attribute_value_name'])));
                $v['attribute_value_price'] = implode(",", array_filter(explode(",", $v['attribute_value_price'])));
            }


            if ($result) {
                $this->ajaxReturn(array('state' => 1, 'data' => $result, 'message' => 'ok'), 'json');
            } else {
                $this->ajaxReturn(array('state' => -1, 'data' => [], 'message' => 'ok'), 'json');
            }
        }
    }
}